package scatter.captcha.rest.service.impl;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import scatter.captcha.pojo.CaptchaStore;
import scatter.captcha.pojo.CaptchaType;
import scatter.captcha.pojo.vo.CaptchaSlideVo;
import scatter.captcha.rest.service.ICaptchaBgImageRandomService;
import scatter.captcha.rest.service.ICaptchaProvider;
import scatter.captcha.rest.service.ICaptchaStoreService;
import scatter.captcha.rest.tools.SlideVerifyCodeTools;

import java.awt.*;
import java.io.IOException;

/**
 * Created by yangwei
 * Created at 2021/1/14 18:25
 */
@Slf4j
@Service
public class SlideCaptchaProviderImpl implements ICaptchaProvider<CaptchaStore<CaptchaSlideVo,Integer>> {

    // 背景图宽度
    private static int bgWidth = 380;
    // 背景图高度
    private static int bgHeight = 160;

    // 滑块宽度
    private static int blockWidth = 45;
    // 滑块高度
    private static int blockHeight = 45;
    // 滑块凹凸圆半径
    private static int circleR = 7;
    // 滑块凹凸边数
    private static int borderNum = 3;

    @Autowired
    private ICaptchaBgImageRandomService iCaptchaBgImageRandomService;

    @Override
    public boolean support(CaptchaType captchaType) {
        return CaptchaType.slide == captchaType;
    }

    @Override
    public CaptchaStore<CaptchaSlideVo, Integer> getCaptcha(CaptchaType captchaType) throws IOException {
        SlideVerifyCodeTools.cutResult image = null;
        int positionX = RandomUtil.randomInt(blockWidth,bgWidth - blockWidth);
        int positionY = RandomUtil.randomInt(0,bgHeight - blockHeight);
        Image scale = ImgUtil.scale(iCaptchaBgImageRandomService.getBgImageRandomInputStream(), bgWidth, bgHeight);
        image = SlideVerifyCodeTools.createImage(ImgUtil.toBufferedImage(scale), blockWidth, blockHeight, circleR, borderNum, positionX, positionY);
        CaptchaSlideVo captchaSlideVo = new CaptchaSlideVo();
        captchaSlideVo.setType(captchaType.name());
        captchaSlideVo.setBgImageBase64Data(image.getBgBase64());
        captchaSlideVo.setSlideImageOffsetY(positionY);
        captchaSlideVo.setSlideImageBase64Data(image.getBlockBase64());
        return CaptchaStore.newCaptchaStore(captchaType, captchaSlideVo, positionX);
    }

}
